import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import {
  ActivityIndicator,
  Alert,
  Modal,
  Pressable,
  RefreshControl,
  ScrollView,
  StyleSheet,
  Text,
  TextInput,
  View,
} from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { useFocusEffect, useRouter } from 'expo-router';
import { Ionicons } from '@expo/vector-icons';
import { Image } from 'expo-image';
import * as ImagePicker from 'expo-image-picker';

import { useAuth } from '@/context/auth-context';
import { apiRequest, uploadImage } from '@/utils/api';
import { encodeRedirectParam } from '@/utils/redirect';

type ApiOrderItem = {
  id: number;
  order_id: number;
  product_id: number;
  title: string;
  price: number;
};

type ApiOrder = {
  id: number;
  order_number: string;
  customer: string;
  contact?: string | null;
  status: string;
  total_amount: number;
  created_at: string;
  items?: ApiOrderItem[];
};

type OrderItem = {
  id: number;
  productId: number;
  title: string;
  price: number;
};

type Order = {
  id: number;
  orderNumber: string;
  customer: string;
  contact: string | null;
  status: string;
  totalAmount: number;
  createdAt: string;
  items: OrderItem[];
};

const STATUS_TEXT: Record<string, string> = {
  pending: '待处理',
  processing: '处理中',
  completed: '已完成',
  canceled: '已取消',
};

const palette = {
  background: '#fdf7fb',
  surface: '#ffffff',
  accent: '#ff8fb1',
  accentDeep: '#ff6a9b',
  border: 'rgba(214, 106, 138, 0.18)',
  textPrimary: '#2f1f2b',
  textMuted: '#78657a',
  textHint: '#9c8aa0',
  danger: '#d64f7c',
  success: '#4fb17a',
};

const mapOrder = (order: ApiOrder): Order => ({
  id: order.id,
  orderNumber: order.order_number,
  customer: order.customer,
  contact: order.contact ?? null,
  status: order.status,
  totalAmount: order.total_amount,
  createdAt: order.created_at,
  items:
    order.items?.map((item) => ({
      id: item.id,
      productId: item.product_id,
      title: item.title,
      price: item.price,
    })) ?? [],
});

const formatCurrency = (value: number) => {
  if (!Number.isFinite(value)) return '¥0.00';
  return `¥${value.toFixed(2)}`;
};

const formatDate = (value: string) => {
  const date = new Date(value);
  if (Number.isNaN(date.getTime())) {
    return value;
  }
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
  });
};

export default function ProfileScreen() {
  const router = useRouter();
  const { user, token, signOut, setViewMode, updateProfile } = useAuth();
  const hasRedirectedRef = useRef(false);

  useEffect(() => {
    if (user || hasRedirectedRef.current) {
      return;
    }

    hasRedirectedRef.current = true;
    const redirect = encodeRedirectParam({ pathname: '/(tabs)/profile' });
    router.replace({ pathname: '/(auth)/login', params: { redirect } });
  }, [router, user]);

  const [orders, setOrders] = useState<Order[]>([]);
  const [isLoading, setLoading] = useState(true);
  const [refreshing, setRefreshing] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [isNameModalVisible, setNameModalVisible] = useState(false);
  const [nameInput, setNameInput] = useState('');
  const [isSavingProfile, setSavingProfile] = useState(false);
  const [isUploadingAvatar, setUploadingAvatar] = useState(false);

  const fetchOrders = useCallback(
    async (refresh = false) => {
      if (!user || !token) {
        return;
      }

      if (refresh) {
        setRefreshing(true);
      } else {
        setLoading(true);
      }

    try {
        const data = await apiRequest<ApiOrder[]>('/orders', { token });
        const normalized = (data ?? []).map(mapOrder);
        const paid = normalized.filter((o) => o.status === 'completed');
        setOrders(paid);
        setError(null);
      } catch (err) {
        const message =
          err instanceof Error ? err.message : '订单数据加载失败，请稍后重试。';
        setError(message);
      } finally {
        if (refresh) {
          setRefreshing(false);
        } else {
          setLoading(false);
        }
      }
    },
    [token, user],
  );

  useFocusEffect(
    useCallback(() => {
      fetchOrders(false);
    }, [fetchOrders]),
  );

  const handleRefresh = useCallback(() => {
    fetchOrders(true);
  }, [fetchOrders]);

  const handleSignOut = useCallback(() => {
    Alert.alert('确认退出当前账号？', '退出后需要重新登录才能继续使用个人功能。', [
      { text: '取消', style: 'cancel' },
      {
        text: '退出登录',
        style: 'destructive',
        onPress: () => {
          signOut();
          router.replace('/(auth)/login');
        },
      },
    ]);
  }, [router, signOut]);

  const handleOpenNameModal = useCallback(() => {
    if (!user) {
      return;
    }
    if (!canEditProfile) {
      Alert.alert('提示', '当前功能仅支持 C 端账号，请使用个人账号登录后再试。');
      return;
    }
    setNameInput(user.displayName?.trim() ?? '');
    setNameModalVisible(true);
  }, [canEditProfile, user]);

  const handleCloseNameModal = useCallback(() => {
    if (isSavingProfile) {
      return;
    }
    setNameModalVisible(false);
  }, [isSavingProfile]);

  const handleSubmitDisplayName = useCallback(async () => {
    if (!user) {
      return;
    }
    if (!canEditProfile) {
      Alert.alert('提示', '当前功能仅支持 C 端账号，请使用个人账号登录后再试。');
      return;
    }

    const trimmed = nameInput.trim();
    if (!trimmed) {
      Alert.alert('提示', '昵称不能为空，请输入新的昵称。');
      return;
    }

    const nameLength = Array.from(trimmed).length;
    if (nameLength > 20) {
      Alert.alert('提示', '昵称最多支持 20 个字符，请适当精简。');
      return;
    }

    const currentName = user.displayName?.trim() ?? '';
    if (trimmed === currentName) {
      setNameModalVisible(false);
      return;
    }

    setSavingProfile(true);
    try {
      await updateProfile({ displayName: trimmed });
      setNameModalVisible(false);
    } catch (err) {
      const message =
        err instanceof Error ? err.message : '更新个人资料失败，请稍后重试。';
      Alert.alert('更新失败', message);
    } finally {
      setSavingProfile(false);
    }
  }, [canEditProfile, nameInput, updateProfile, user]);

  const handleChangeAvatar = useCallback(async () => {
    if (!user) {
      return;
    }

    if (!canEditProfile) {
      Alert.alert('提示', '当前功能仅支持 C 端账号，请使用个人账号登录后再试。');
      return;
    }

    if (!token) {
      Alert.alert('提示', '登录状态已过期，请重新登录后再试。');
      return;
    }

    const permission = await ImagePicker.requestMediaLibraryPermissionsAsync();
    if (permission.status !== 'granted') {
      Alert.alert('权限不足', '请在系统设置中开启相册访问权限，以更换头像。');
      return;
    }

    const result = await ImagePicker.launchImageLibraryAsync({
      mediaTypes: ['images'],
      allowsMultipleSelection: false,
      quality: 1,
    });

    if (result.canceled || !result.assets?.length) {
      return;
    }

    const asset = result.assets[0];
    const fileName = asset.fileName ?? asset.uri.split('/').pop() ?? 'avatar.jpg';
    const fileType = asset.mimeType ?? 'image/jpeg';

    setUploadingAvatar(true);
    try {
      const uploaded = await uploadImage(
        { uri: asset.uri, name: fileName, type: fileType },
        token,
        '/profile/avatar/upload',
      );
      const nextAvatar =
        uploaded.preview_url ||
        uploaded.thumb_url ||
        uploaded.original_url ||
        uploaded.url ||
        '';
      if (!nextAvatar) {
        throw new Error('头像上传失败，请稍后重试。');
      }
      await updateProfile({ avatarUrl: nextAvatar });
    } catch (err) {
      const message =
        err instanceof Error ? err.message : '头像更新失败，请稍后重试。';
      Alert.alert('更新失败', message);
    } finally {
      setUploadingAvatar(false);
    }
  }, [canEditProfile, token, updateProfile, user]);

  const displayName = useMemo(() => {
    if (!user) {
      return '';
    }
    if (user.displayName && user.displayName.trim().length > 0) {
      return user.displayName.trim();
    }

    const fallback = (user.phone && user.phone.trim()) || user.username || '';
    if (!fallback) {
      return '用户';
    }
    const suffix = fallback.slice(-4);
    return suffix ? `用户 ${suffix}` : '用户';
  }, [user]);

  const stats = useMemo(() => {
    if (!orders.length) {
      return { totalAmount: 0, completed: 0 };
    }

    return orders.reduce(
      (acc, order) => {
        acc.totalAmount += order.totalAmount;
        if (order.status === 'completed') {
          acc.completed += 1;
        }
        return acc;
      },
      { totalAmount: 0, completed: 0 },
    );
  }, [orders]);

  const latestOrders = useMemo(
    () =>
      [...orders].sort(
        (a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime(),
      ),
    [orders],
  );

  if (!user) {
    return null;
  }

  const canEditProfile = (user.role ?? user.channel) === 'customer';
  const phoneLabel = (user.phone && user.phone.trim()) || user.username;
  const avatarUrl =
    typeof user.avatarUrl === 'string' && user.avatarUrl ? user.avatarUrl.trim() : '';
  const displayInitial = displayName.trim() ? displayName.trim().slice(0, 1) : '用';
  const profileHintText = canEditProfile
    ? '轻提示：点击头像或昵称即可修改个人资料。'
    : '当前为商户账号，暂不支持修改头像与昵称。';

  return (
    <SafeAreaView style={styles.safeArea}>
      <ScrollView
        style={styles.scroll}
        contentContainerStyle={styles.container}
        refreshControl={
          <RefreshControl refreshing={refreshing} onRefresh={handleRefresh} />
        }
      >
        <View style={styles.card}>
          <View style={styles.profileHeader}>
            <Pressable
              style={[styles.avatar, !canEditProfile && styles.avatarDisabled]}
              onPress={handleChangeAvatar}
              disabled={!canEditProfile || isUploadingAvatar}
            >
              {avatarUrl ? (
                <Image source={{ uri: avatarUrl }} style={styles.avatarImage} contentFit="cover" />
              ) : (
                <Text style={styles.avatarInitial}>{displayInitial}</Text>
              )}
              {isUploadingAvatar ? (
                <View style={styles.avatarOverlay}>
                  <ActivityIndicator color="#ffffff" />
                </View>
              ) : null}
            </Pressable>
            <View style={styles.profileInfo}>
              {canEditProfile ? (
                <Pressable style={styles.nameRow} onPress={handleOpenNameModal}>
                  <Text style={styles.profileName}>{displayName}</Text>
                  <Text style={styles.editHint}>点击修改昵称</Text>
                </Pressable>
              ) : (
                <View style={styles.nameRow}>
                  <Text style={styles.profileName}>{displayName}</Text>
                  <Text style={styles.editHintDisabled}>商户账号暂不支持修改</Text>
                </View>
              )}
              <Text style={styles.profileChannel}>
                {user.channel === 'merchant' ? '商户账号' : '个人账号'}
              </Text>
              <Text style={styles.profileMeta}>手机号：{phoneLabel}</Text>
            </View>
          </View>

          <Text style={styles.profileHint}>{profileHintText}</Text>

          <View style={styles.overview}>
            <View style={styles.overviewItem}>
              <Text style={styles.overviewLabel}>订单总数</Text>
              <Text style={styles.overviewValue}>{orders.length}</Text>
            </View>
            <View style={styles.overviewItem}>
              <Text style={styles.overviewLabel}>已完成</Text>
              <Text style={styles.overviewValue}>{stats.completed}</Text>
            </View>
            <View style={styles.overviewItem}>
              <Text style={styles.overviewLabel}>累计金额</Text>
              <Text style={styles.overviewValue}>{formatCurrency(stats.totalAmount)}</Text>
            </View>
          </View>
        </View>

        {/* 鎴戠殑鍐呭蹇嵎鍏ュ彛 */}
        <View style={[styles.card, styles.section]}>
          <Text style={styles.sectionTitle}>我的内容</Text>
          <Pressable style={styles.settingRow} onPress={() => router.push('/purchases')}>
            <Text style={styles.settingLabel}>已购商品</Text>
            <Ionicons name="chevron-forward" size={18} color={palette.textHint} />
          </Pressable>
          <Pressable style={styles.settingRow} onPress={() => router.push('/history')}>
            <Text style={styles.settingLabel}>观看历史</Text>
            <Ionicons name="chevron-forward" size={18} color={palette.textHint} />
          </Pressable>
          <Pressable style={styles.settingRow} onPress={() => router.push('/favorites')}>
            <Text style={styles.settingLabel}>收藏/喜欢</Text>
            <Ionicons name="chevron-forward" size={18} color={palette.textHint} />
          </Pressable>
          <Pressable style={styles.settingRow} onPress={() => router.push('/leaderboard')}>
            <Text style={styles.settingLabel}>消费总榜</Text>
            <Ionicons name="chevron-forward" size={18} color={palette.textHint} />
          </Pressable>
        </View>

        {user.role === 'merchant' ? (
          <View style={[styles.card, styles.section]}>
            <Pressable
              style={styles.settingRow}
              onPress={() => {
                setViewMode('merchant');
                router.replace('/(merchant)/overview');
              }}
            >
              <Text style={styles.settingLabel}>切换至商户端</Text>
              <Ionicons name="chevron-forward" size={18} color={palette.textHint} />
            </Pressable>
          </View>
        ) : null}

        <View style={[styles.card, styles.section]}>
          <View style={styles.sectionHeader}>
            <Text style={styles.sectionTitle}>最近已支付订单</Text>
          </View>

          {isLoading ? (
            <View style={styles.centered}>
              <ActivityIndicator color={palette.accentDeep} />
              <Text style={styles.loadingText}>正在加载订单信息…</Text>
            </View>
          ) : error ? (
            <View style={styles.errorBox}>
              <Text style={styles.errorText}>{error}</Text>
            </View>
          ) : latestOrders.length === 0 ? (
            <View style={styles.emptyBox}>
              <Text style={styles.emptyTitle}>暂无订单</Text>
              <Text style={styles.emptyText}>完成第一笔订单后，这里会展示最新进展。</Text>
            </View>
          ) : (
            latestOrders.map((order) => (
              <View key={order.id} style={styles.orderCard}>
                <View style={styles.orderHeader}>
                  <Text style={styles.orderNumber}>{order.orderNumber}</Text>
                  <View style={styles.statusBadge}>
                    <Text style={styles.statusText}>
                      {STATUS_TEXT[order.status] ?? order.status}
                    </Text>
                  </View>
                </View>
                <Text style={styles.orderAmount}>{formatCurrency(order.totalAmount)}</Text>
                <Text style={styles.orderDate}>{formatDate(order.createdAt)}</Text>
                {order.items.length > 0 ? (
                  <View style={styles.itemList}>
                    {order.items.map((item) => (
                      <View key={item.id} style={styles.itemRow}>
                        <Text style={styles.itemTitle}>{item.title}</Text>
                        <Text style={styles.itemPrice}>{formatCurrency(item.price)}</Text>
                      </View>
                    ))}
                  </View>
                ) : null}
                {order.contact ? (
                  <Text style={styles.orderContact}>联系人：{order.contact}</Text>
                ) : null}
              </View>
            ))
          )}
        </View>
        <View style={[styles.card, styles.section, styles.signOutCard]}>
          <Text style={styles.signOutHint}>退出后需重新登录才能继续使用个人功能。</Text>
          <Pressable style={styles.signOutButton} onPress={handleSignOut}>
            <Text style={styles.signOutText}>退出登录</Text>
          </Pressable>
        </View>
      </ScrollView>
      <Modal
        visible={isNameModalVisible}
        transparent
        animationType="fade"
        onRequestClose={handleCloseNameModal}
      >
        <View style={styles.modalBackdrop}>
          <View style={styles.modalCard}>
            <Text style={styles.modalTitle}>修改昵称</Text>
            <TextInput
              style={styles.modalInput}
              value={nameInput}
              onChangeText={setNameInput}
              placeholder="请输入新的昵称"
              placeholderTextColor={palette.textHint}
              maxLength={20}
              editable={!isSavingProfile}
              autoFocus
            />
            <View style={styles.modalActions}>
              <Pressable
                style={[styles.modalButton, styles.modalCancel, isSavingProfile && styles.modalButtonDisabled]}
                onPress={handleCloseNameModal}
                disabled={isSavingProfile}
              >
                <Text style={[styles.modalButtonText, styles.modalCancelText]}>取消</Text>
              </Pressable>
              <Pressable
                style={[styles.modalButton, styles.modalConfirm, isSavingProfile && styles.modalButtonDisabled]}
                onPress={handleSubmitDisplayName}
                disabled={isSavingProfile}
              >
                {isSavingProfile ? (
                  <ActivityIndicator color="#ffffff" />
                ) : (
                  <Text style={[styles.modalButtonText, styles.modalConfirmText]}>保存</Text>
                )}
              </Pressable>
            </View>
          </View>
        </View>
      </Modal>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  safeArea: {
    flex: 1,
    backgroundColor: palette.background,
  },
  scroll: {
    flex: 1,
  },
  container: {
    padding: 20,
    gap: 16,
  },
  card: {
    borderRadius: 28,
    backgroundColor: palette.surface,
    padding: 20,
    shadowColor: 'rgba(214, 106, 138, 0.2)',
    shadowOpacity: 0.2,
    shadowOffset: { width: 0, height: 8 },
    shadowRadius: 16,
    elevation: 6,
    gap: 20,
  },
  profileHeader: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: 16,
  },
  avatar: {
    width: 72,
    height: 72,
    borderRadius: 36,
    backgroundColor: palette.accent,
    justifyContent: 'center',
    alignItems: 'center',
    overflow: 'hidden',
    position: 'relative',
  },
  avatarDisabled: {
    opacity: 0.6,
  },
  avatarImage: {
    width: '100%',
    height: '100%',
  },
  avatarInitial: {
    fontSize: 32,
    color: palette.textPrimary,
    fontWeight: '700',
  },
  avatarOverlay: {
    ...StyleSheet.absoluteFillObject,
    backgroundColor: 'rgba(0,0,0,0.35)',
    justifyContent: 'center',
    alignItems: 'center',
  },
  profileInfo: {
    flex: 1,
    gap: 6,
  },
  nameRow: {
    gap: 4,
  },
  profileName: {
    fontSize: 22,
    fontWeight: '700',
    color: palette.textPrimary,
  },
  editHint: {
    fontSize: 12,
    color: palette.textHint,
  },
  editHintDisabled: {
    fontSize: 12,
    color: palette.textHint,
  },
  profileChannel: {
    fontSize: 13,
    color: palette.accentDeep,
    fontWeight: '600',
  },
  profileMeta: {
    fontSize: 13,
    color: palette.textHint,
  },
  profileHint: {
    fontSize: 12,
    color: palette.textMuted,
  },
  signOutButton: {
    borderRadius: 999,
    paddingHorizontal: 16,
    paddingVertical: 8,
    borderWidth: 1,
    borderColor: palette.border,
    alignSelf: 'center',
  },
  signOutText: {
    fontSize: 12,
    color: palette.textMuted,
    fontWeight: '600',
  },
  signOutCard: {
    alignItems: 'center',
    gap: 12,
  },
  signOutHint: {
    fontSize: 12,
    color: palette.textHint,
    textAlign: 'center',
  },
  settingRow: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    paddingVertical: 12,
  },
  settingLabel: {
    fontSize: 14,
    color: palette.textPrimary,
    fontWeight: '600',
  },
  overview: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    gap: 12,
  },
  overviewItem: {
    flex: 1,
    backgroundColor: 'rgba(255, 143, 177, 0.08)',
    borderRadius: 20,
    paddingVertical: 18,
    paddingHorizontal: 14,
    gap: 8,
  },
  overviewLabel: {
    fontSize: 12,
    color: palette.textHint,
  },
  overviewValue: {
    fontSize: 18,
    fontWeight: '700',
    color: palette.textPrimary,
  },
  section: {
    gap: 16,
  },
  sectionHeader: {
    gap: 4,
  },
  sectionTitle: {
    fontSize: 18,
    fontWeight: '700',
    color: palette.textPrimary,
  },
  sectionHint: {
    fontSize: 12,
    color: palette.textHint,
  },
  centered: {
    alignItems: 'center',
    gap: 10,
  },
  loadingText: {
    fontSize: 13,
    color: palette.textMuted,
  },
  errorBox: {
    borderRadius: 16,
    padding: 16,
    borderWidth: 1,
    borderColor: 'rgba(214,79,124,0.3)',
    backgroundColor: 'rgba(214,79,124,0.08)',
  },
  errorText: {
    fontSize: 13,
    color: palette.danger,
  },
  emptyBox: {
    alignItems: 'center',
    gap: 6,
    paddingVertical: 32,
  },
  emptyTitle: {
    fontSize: 16,
    fontWeight: '600',
    color: palette.textPrimary,
  },
  emptyText: {
    fontSize: 13,
    color: palette.textHint,
  },
  orderCard: {
    borderRadius: 20,
    borderWidth: 1,
    borderColor: palette.border,
    padding: 16,
    gap: 10,
  },
  orderHeader: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
  },
  orderNumber: {
    fontSize: 14,
    fontWeight: '600',
    color: palette.textPrimary,
  },
  statusBadge: {
    borderRadius: 999,
    paddingHorizontal: 12,
    paddingVertical: 6,
    backgroundColor: 'rgba(79,177,122,0.12)',
  },
  statusText: {
    fontSize: 12,
    fontWeight: '600',
    color: palette.success,
  },
  orderAmount: {
    fontSize: 18,
    fontWeight: '700',
    color: palette.textPrimary,
  },
  orderDate: {
    fontSize: 12,
    color: palette.textHint,
  },
  itemList: {
    gap: 6,
  },
  itemRow: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
  },
  itemTitle: {
    fontSize: 13,
    color: palette.textMuted,
    flex: 1,
  },
  itemPrice: {
    fontSize: 13,
    fontWeight: '600',
    color: palette.textPrimary,
  },
  orderContact: {
    marginTop: 6,
    fontSize: 12,
    color: palette.textHint,
  },
  modalBackdrop: {
    flex: 1,
    backgroundColor: 'rgba(0,0,0,0.45)',
    justifyContent: 'center',
    alignItems: 'center',
    paddingHorizontal: 24,
  },
  modalCard: {
    width: '100%',
    maxWidth: 360,
    borderRadius: 24,
    backgroundColor: '#fff',
    padding: 20,
    gap: 16,
  },
  modalTitle: {
    fontSize: 18,
    fontWeight: '700',
    color: palette.textPrimary,
  },
  modalInput: {
    borderWidth: 1,
    borderColor: palette.border,
    borderRadius: 12,
    paddingHorizontal: 14,
    paddingVertical: 10,
    fontSize: 15,
    color: palette.textPrimary,
    backgroundColor: '#fff',
  },
  modalActions: {
    flexDirection: 'row',
    justifyContent: 'flex-end',
    gap: 12,
  },
  modalButton: {
    borderRadius: 999,
    paddingHorizontal: 18,
    paddingVertical: 10,
    alignItems: 'center',
    justifyContent: 'center',
  },
  modalCancel: {
    borderWidth: 1,
    borderColor: palette.border,
    backgroundColor: '#fff',
  },
  modalConfirm: {
    backgroundColor: palette.accent,
  },
  modalButtonDisabled: {
    opacity: 0.6,
  },
  modalButtonText: {
    fontSize: 14,
    fontWeight: '600',
    color: palette.textPrimary,
  },
  modalCancelText: {
    color: palette.textMuted,
  },
  modalConfirmText: {
    color: palette.textPrimary,
  },
});





